import datetime as dt
import time
import json
from pathlib import Path
import yagmail
import os




class  StepStatus:
    def __init__(self):
        self.idx = -1
        self.count = 0
        self.log = 0

g_status_dict = {}
g_file_path = "/f/cbops/daily_task/"
g_config_name = "config.json"

class Log:
    def __init__(self, file):
        self.handle = open(file, "at")
            
    def msg_to_log(self,msg):
        time =  dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.handle.write(time +" " + msg +"\n")

def send_email(result, inform):

    yag = yagmail.SMTP(user = '1600671800@qq.com', password = 'xrlorubavfmfjcde', host = 'smtp.qq.com')
    contents = ['File saved sucessfully ' + str(result)]
    for ele in inform:
        yag.send(ele, 'subject', contents)

def read_config():
    global g_config_name
    global g_file_path
    raw_file = open( g_file_path + g_config_name)
    json_file = json.load(raw_file)
    print("read config")
    return json_file

def get_status(idx):

    if (idx not in g_status_dict):
        curr_status = StepStatus()
        curr_status.idx = idx
        curr_status.flag = 0
        curr_status.log = 0
        g_status_dict.setdefault(idx, curr_status)        
    return g_status_dict[idx]

#修改date要注意，可能需要去修改配置文件
def loop():
    global g_config_name
    global g_file_path
    log = Log(g_file_path+ "eod.log")
    file_json = read_config()

    pre = dt.datetime.now() - dt.timedelta(hours = 24)
    date = pre.strftime("%Y%m%d")

    if file_json.get("update_date") == date:
        print("today updated")
        return 
    
    file_json["update_date"] = date

    global g_config_name
    with open( g_file_path + g_config_name,'w') as f:
        json.dump(file_json, f)

    break_cond = dt.datetime.now() + dt.timedelta(hours = 2)
    #break_cond = dt.datetime.now() + dt.timedelta(minutes = 10)
    start = dt.datetime.now()
    curr = start

    print(start)
    exists_file = []
    log.msg_to_log("record  " +date+" file")
    while curr < break_cond:
        curr = dt.datetime.now()
        diff = curr - start
        time.sleep(120)
        
        #print("break_cond" + str(break_cond))
        #print("curr" + str(curr))

        diff_minute = int( diff.seconds/60);
       
        for i in range(2, 8):
            curr_json = file_json.get(str(i))
            file_list = curr_json.get("file")
            time_list = curr_json.get("time")
            #print(file_list)
     
            
            log.msg_to_log("diff: " + str(diff_minute) + "time_range: "+ str(time_list[0]) +"--" + str(time_list[1]))
            if diff_minute in range(time_list[0],  time_list[1]):
                curr_status = get_status(i)
                log.msg_to_log( "time_range: " + str(time_list[0]) +"--" + str(time_list[1]))

                for ele in file_list:
                   
                    if "_" in ele or (ele == ".csv"):
                        file = Path(g_file_path + date + ele)
                       
                        if not file.exists():
                            log.msg_to_log(file.name + " not find")
                            curr_status.flag = 0
                            break  
                        else:
                            log.msg_to_log(file.name + " find")
                            curr_status.flag = 1
                            exists_file.append(file)

                    else:

                        file = Path(g_file_path + ele)
                        if not file.exists():
                            log.msg_to_log(file.name + " not find")
                            curr_status.flag = 0
                            break  
                        else:
                            log.msg_to_log(file.name + " find")
                            curr_status.flag = 1
                            exists_file.append(file)

            else:
                curr_status = get_status(i)
                if diff_minute > time_list[1]  and curr_status.log == 0 :
                    if(curr_status.flag == 0 ):
                        log.msg_to_log("step " +str(i)+" file cant find")
                    else:
                        log.msg_to_log("step " +str(i)+" file ok")
                    curr_status.log = 1
    result = []
    for key in g_status_dict:
        result.append( g_status_dict[key].flag)
    
    exists_file = list(set(exists_file))
    for file in exists_file:
        log.msg_to_log(file.name + " removed")
        os.remove(file)
    if 0 in result:
        send_email(result, file_json.get("inform"))
loop()
